"""
    dict 客户端： 与用户交互发起请求
"""
from socket import *
from threading import Thread
from time import sleep
import sys
import re

# 服务器地址
SERVER_ADDR=("127.0.0.1",8888)

# 具体向服务端发送请求
class Handle:
    @staticmethod
    def check(info):
        if re.findall("^\w{6,}$", info):
            return True
        return False

    def __init__(self):
        self.sock = self._connect()

    def _connect(self):
        sock=socket(AF_INET,SOCK_STREAM)
        sock.connect(SERVER_ADDR)
        return sock

    # 发起注册请求
    def do_register(self,name,password):
        if Handle.check(name) and Handle.check(password):
            msg="R\t%s\t%s"%(name,password)
            self.sock.send(msg.encode())
            result=self.sock.recv(128)
            if result == b"T":
                print("注册成功")
            else:
                print("注册失败")

    def do_exit(self):
        self.sock.send(b"E")
        self.sock.close()
        sys.exit("谢谢使用")
    # 发起登录请求
    def do_login(self, name, password):
        msg = "L\t%s\t%s" % (name, password)
        self.sock.send(msg.encode())
        result=self.sock.recv(128)
        if result == b"T":
            print("登录成功")
            return True
        else:
            print("登录失败")

    def do_query(self):
        while True:
            word=input("请输入要查询的单词：")
            if not word or word=="##":
                break # 结束查单词
            msg="Q\t%s"%word
            self.sock.send(msg.encode())
            response=self.sock.recv(1024).decode()
            tmp=response.split("\t",1) # 根据协议作出分割
            if tmp[0] == "T":
                print("%s : %s\n"%(word,tmp[1]))
            else:
                print("查无此词\n")
    # 历史记录
    def do_hist(self):
        self.sock.send(b"H")
        response=self.sock.recv(1024).decode()
        tmp = response.split("\t") #根据协议分割
        if tmp[0]=="T":
            for row in tmp[1].split(";"):
                print(row)
        else:
            print("您还没有查询记录")

# 与用户交互
class DICTView:
    def __init__(self):
        self.handle=Handle()

    def menu_2(self):
        while True:
            print("""
            ============Query=============
            1.查单词    2.历史记录     3.注销
            ==============================
            """)
            cmd=input("请输入选项：")
            if cmd=="1":
                self.handle.do_query()
            elif cmd=="2":
                self.handle.do_hist()
            elif cmd=="3":
                break
            else:
                print("请输入正确选项！")
    def menu_1(self):
        while True:
            print("""
            ===========Welcome============
            1.登录      2.注册       3.退出
            ==============================
            """)
            cmd=input("请输入选项：")
            if cmd=="1":
                usrname=input("username:")
                usrpasswd=input("password:")
                if self.handle.do_login(usrname,usrpasswd):
                    self.menu_2()  # 进入登录界面
            elif cmd=="2":
                name=input("usrname:")
                passwd=input("password:")
                self.handle.do_register(name,passwd)
            elif cmd=="3":
                self.handle.do_exit()
            else:
                print("请输入正确选项！")

    def main(self):
        while True:
            self.menu_1()

if __name__ == '__main__':
    dict=DICTView()
    dict.main()

